global class EquipmentCountBatch implements Database.Batchable<Equipment__c>{

    global Iterable<Equipment__c> start(Database.batchableContext info){
       return [select Id, FromFlow__c ,EndDate__c,RelatedWorkOrders__c,CreatedDate,CurrentServiceCoverage__c from Equipment__c];
    }
    private Decimal getOtherDecimal(Decimal inp ){
        if(inp == 0.0) return 1.0;
        return 0.0;
    }
    global void execute(Database.batchableContext info, List<Equipment__c> equips) {
         Map<String,String> eResMap = new Map<String,String>();
        Datetime d = Datetime.newInstance(System.today().year(), 1, 1);
        Map<String,Equipment__c> equipMap = new Map<String,Equipment__c>();
        Map<String,Set<String> >yearMap = new Map<String,Set<String>>();

        for(Equipment__c e :equips ){
            equipMap.put(e.Id,e);
            if(e.RelatedWorkOrders__c != null && e.CreatedDate >=d )eResMap.put(e.Id , '工程');
            Set<String> years = yearMap.containsKey(e.Id) ? yearMap.get(e.Id) : new Set<String>();
            if(e.EndDate__c != null ) years.add(e.EndDate__c.year()+'年');
            yearMap.put(e.Id,years);
        }

        Set<String> types = new Set<String>{'应用','工程'};
     
        for(AggregateResult arg : [select count(Id) total,ServiceManufacture__c ,Case__r.Servicetype__c 
            from WorkOrder__c where Case__r.Servicetype__c in:types 
            and CreatedDate >=: Datetime.newInstance(System.today().year(), 1, 1)
            and ServiceManufacture__c in :equipMap.keySet()
            and Status__c = '完成'
            Group by ServiceManufacture__c,Case__r.Servicetype__c ]){

            String eid = (String)arg.get('ServiceManufacture__c');
            Integer cnt = (Integer) arg.get('total');
            String type = (String)arg.get('Servicetype__c');
            String res = eResMap.containsKey(eid)?eResMap.get(eid): '';
            if(!res.contains(type))res+=type;
            eResMap.put(eid, cnt > 0 ? res : null );

        }
       
        for(AggregateResult arg : [select count(Id) total ,calendar_year(Install_End_Datetime__c) year,ServiceManufacture__c 
            from WorkOrder__c where ServiceManufacture__c in :equipMap.keySet()
            and RecordType.developerName = 'MaintenanceOrder' 
            and Install_End_Datetime__c != null 
            and Status__c = '完成' Group by calendar_year(Install_End_Datetime__c),ServiceManufacture__c   ]){
            Integer cnt = (Integer) arg.get('total');
            String eid = (String)arg.get('ServiceManufacture__c');
            Set<String> years = yearMap.containsKey(eid) ? yearMap.get(eid) : new Set<String>();
            if(cnt > 0 )years.add(arg.get('year')+'年');
            yearMap.put(eid,years);
           
        }


        for(String eid : equipMap.keySet()){
            Equipment__c e = equipMap.get(eid);

            e.FromFlow__c = getOtherDecimal(e.FromFlow__c);
            e.CurrentServiceCoverage__c = eResMap.get(eid);
            Set<String> years = yearMap.containsKey(eid) ? yearMap.get(eid) : new Set<String>();
           if(!years.isEmpty()) e.ServiceYear__c = String.join(new List<String>(years), ',');
        }
        try{
            update equipMap.values();
        }catch(Exception e){
            Task t = new Task();
            t.OwnerId  =[select Id from User where Name =:Label.CoverOfEquipmentFailure limit 1].Id;
            t.Subject = '工程产培标记仪器覆盖率失败';
            t.Description = '工程产培标记仪器覆盖率失败:'+e.getMessage();
            t.WhatId  = equips[0].Id ;
            t.ActivityDate = System.today();
            insert t ; 

        }
       
       /*Map<Id,Equipment__c> eps = new Map<Id,Equipment__c>();
            for(Equipment__c e:s){
                e.ServiceHours__c = 0;
                e.MalfunctionFrequency__c = 0;
                eps.put(e.Id,e);
            }
            //服务工单记录类型
            Id serType = Utils.getRecordTypeIdByDevNameAndObjName('服务工单','WorkOrder__c');
            //保养工单记录类型
            Id mainType = Utils.getRecordTypeIdByDevNameAndObjName('保养工单','WorkOrder__c');
            //服务工单
            Map<Id,WorkOrder__c> sers = new Map<Id,WorkOrder__c>();
            for(WorkOrder__c w: [select Id, ServiceManufacture__c, Install_Start_Datetime__c, Install_End_Datetime__c 
            from WorkOrder__c where  CreatedDate = last_month and RecordTypeId =:serType and ServiceManufacture__c =: eps.keySet()]){
                sers.put(w.ServiceManufacture__c,w);
                if(eps.containsKey(w.ServiceManufacture__c)){
                    Equipment__c e = eps.get(w.ServiceManufacture__c);
                    
                    e.MalfunctionFrequency__c += 1;
                    if(w.Install_End_Datetime__c != null && w.Install_Start_Datetime__c != null){
                        e.ServiceHours__c += (w.Install_End_Datetime__c.getTime() - w.Install_Start_Datetime__c.getTime())/3600000.0; 

                    }
                }
            }
            
            //保养工单
            for(WorkOrder__c w: [select Id, ServiceManufacture__c, Install_Start_Datetime__c, Install_End_Datetime__c 
            from WorkOrder__c where CreatedDate = last_month and RecordTypeId =:mainType and ServiceManufacture__c =: eps.keySet()]){
                sers.put(w.ServiceManufacture__c,w);
                if(eps.containsKey(w.ServiceManufacture__c)){
                    Equipment__c e = eps.get(w.ServiceManufacture__c);
                    if(w.Install_End_Datetime__c != null && w.Install_Start_Datetime__c != null){
                        e.ServiceHours__c += (w.Install_End_Datetime__c.getTime() - w.Install_Start_Datetime__c.getTime())/3600000.0; 

                    }
                }
            }

            update eps.values();
            */
    }
    
    global void finish(Database.BatchableContext BC) {

    }
}